﻿package com.PlantVsZombies.db.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.PlantVsZombies.db.model.Record;
import com.PlantVsZombies.util.DBUtil;

public class RecordDao {
	QueryRunner qr = new QueryRunner(DBUtil.getDataSource());

	public boolean insertRecord(Record record) {
		String sql = "insert into t_record(player, data, pattern, time) values(?,?,?,?)";
		Object[] params = { record.getPlayer(), record.getData(), record.getPattern(), new Date() };
		try {
			return qr.update(sql, params) > 0;
		} catch (SQLException e) {
			System.out.println("插入存档失败");
			return false;
		}
	}

	public List<Record> selectAll() {
		String sql = "select * from t_record order by time";
		try {
			return  (List<Record>) qr.query(sql, new BeanListHandler(Record.class));
		} catch (SQLException e) {
			System.out.println("查询存档出错");
			return new ArrayList<>();
		}
	}
	
	public Record select(Integer recordId) {
		String sql = "select * from t_record where recordId = " + recordId;
		try {
			return  (Record) qr.query(sql, new BeanHandler(Record.class));
		} catch (SQLException e) {
			System.out.println("查询存档出错");
			return null;
		}
	}
}
